<template>
  <div class="page-wrap">
    <template v-if="current">
      <div class="left-list">
        <div
          @click="current = item"
          class="list-item"
          v-for="item in dataList"
          :key="item.id"
          :style="{ background: item.id == current.id ? '#EEE' : '#FFF' }"
        >
          {{ item.title }}
        </div>
      </div>
      <div class="right-form">
        <el-input @input="handleInput" v-model="current.title"><template slot="prepend">标题</template> </el-input>
        <div style="height: 4px"></div>
        <el-input @input="handleInput" v-model="current.site"><template slot="prepend">站点</template> </el-input>
        <div style="height: 4px"></div>

        <template v-for="(it, inx) in current.accountLis">
          <div class="account-title" :key="'d' + inx">
            账号{{ inx + 1 }}
            <div style="flex: 1"></div>
            <el-switch
              :disabled="current.accountLis.length == 1 || it.active ? true : false"
              @change="handleSwitchChange($event, inx)"
              active-text="激活"
              v-model="it.active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :key="'c' + inx"
            >
            </el-switch>
          </div>
          <el-input @input="handleInput" v-model="it.account" :key="'a' + inx"><template slot="prepend">账号</template> </el-input>
          <div style="height: 4px" :key="'l1' + inx"></div>
          <el-input @input="handleInput" v-model="it.password" :key="'b' + inx"><template slot="prepend">密码</template> </el-input>
        </template>
        <div class="account-add">
          <el-button style="transform: scale(0.8)" @click="handleAddAccount" type="primary" icon="el-icon-plus" circle></el-button>
        </div>
      </div>
    </template>
    <div v-if="showOutput" class="data-output">
      <el-input style="z-index: 9999" @click="event.stopPropagation()" v-model="scriptStr" rows="20" type="textarea"> </el-input>
      <el-button type="success" @click="showOutput = false">关闭返回</el-button>
      <el-button type="parimary" @click="handleDataInput">开始导入</el-button>
    </div>

    <div class="bottom-btn">
      <el-button @click="handleDataOutput" type="primary" icon="el-icon-sort" circle></el-button>
      <el-button @click="handleAdd" type="success" icon="el-icon-plus" circle></el-button>
      <el-button @click="handleRowDelete" type="danger" icon="el-icon-delete" circle></el-button>
    </div>
  </div>
</template>
<script>
import _ from 'lodash'
var saveIdAutoEnterRule = _.debounce((e) => {
  chrome.runtime.sendMessage({
    action: 'bgRequest',
    params: {
      url: `pushObs`,
      method: 'POST',
      body: {
        name: 'IdAutoEnterRule',
        content: JSON.stringify(e),
      },
    },
  })
}, 1000)

function Guid(n = 3) {
  const G = () => {
    return (((Math.random() * 0.8 + 0.1) * 0x100000) | 0).toString(16).toLocaleUpperCase()
  }
  if (n == 1) return G()
  return `${G()}-${G()}-${G()}`
}

async function SWAPI(action, params = {}) {
  return await chrome.runtime.sendMessage({ action, params })
}
export default {
  name: 'autoPwdManage',
  data() {
    return {
      showOutput: false,
      centerDialogVisible: false,
      current: null,
      dataList: [],
      scriptStr: '',
    }
  },
  created() {
    this.getData()
    // console.log(_)
  },
  methods: {
    handleInput() {
      // console.log('input')
      saveIdAutoEnterRule(this.dataList)
    },

    handleAdd(e, r) {
      this.dataList.push({
        title: Guid(1),
        id: Guid(),
        site: '',
        accountLis: [{ account: '', password: '', active: true }],
      })
      this.current = this.dataList[this.dataList.length - 1]
    },

    handleDataInput() {
      try {
        const data = JSON.parse(this.scriptStr)
        this.dataList = data
        this.current = null
        saveIdAutoEnterRule(data)
        this.$nextTick(() => {
          this.current = this.dataList[0]
        })
      } catch (e) {
        console.log(e)
      }
    },
    handleDataOutput() {
      this.showOutput = !this.showOutput
      if (this.showOutput) this.scriptStr = JSON.stringify(this.dataList)
    },

    handleAddAccount() {
      this.current.accountLis.push({ account: '', password: '', active: false })
    },
    handleSwitchChange(e, inx) {
      // 控件已经禁用了取消激活的操作，这里只有激活才会触发
      for (let x = 0; x < this.current.accountLis.length; x++) {
        if (x != inx) this.current.accountLis[x].active = false
      }
      saveIdAutoEnterRule(this.dataList)
    },
    async handleRowDelete() {
      if (this.dataList.length < 2) return this.$message.info('最后一条，无法删除')
      try {
        await this.$confirm('确认要继续删除操作吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'msgbox',
        })
        const delInx = this.dataList.findIndex((e) => e.id == this.current.id)
        this.dataList.splice(delInx, 1)
        this.current = this.dataList[0]
        saveIdAutoEnterRule(this.dataList)
      } catch (error) {
        console.log(error)
      }
    },
    async getData() {
      // let res = await SWAPI('getIdAutoEnterRule')
      let res = await chrome.runtime.sendMessage({ action: 'bgRequest', params: { url: `pullObs?name=IdAutoEnterRule` } })
      console.log('getData', res)
      res = res.data ? JSON.parse(res.data) : {}
      if (JSON.stringify(res) != '{}') {
        this.dataList = res
        console.log(res)
      } else {
        this.dataList = [
          {
            title: Guid(1),
            id: Guid(),
            site: '',
            accountLis: [{ account: '', password: '', active: true }],
          },
        ]
      }
      this.current = this.dataList[0]
    },
  },
}
</script>

<style lang="scss" scope>
.page-wrap {
  display: flex;
}

.left-list {
  display: flex;
  flex-direction: column;
  border-right: 1px solid #5fb878;
  width: 120px;
  height: calc(100vh - 51px);
  overflow: auto;
}
.account-add {
  padding-top: 6px;
  width: 100%;
  text-align: left;
}

.account-title {
  margin-top: 8px;
  padding: 0 6px;
  height: 32px;
  display: flex;
  align-items: center;
  border-top: 1px solid #ddd;
}
.list-item {
  display: flex;
  align-items: center;
  height: 28px;
  flex-shrink: 0;
  // background: #eee;
  padding: 0 10px;
  border-bottom: 1px #5fb878 solid;
}

.list-item::nth-child(odd) {
  background: #fff;
}

.right-form {
  padding: 6px;
  box-sizing: border-box;
  position: relative;
  flex: 1;
  height: calc(100vh - 51px);
  overflow: auto;
}
.bottom-btn {
  position: fixed;
  bottom: 18px;
  right: 18px;
}
.data-output {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
}

@media (max-width: 720px) {
  .msgbox {
    width: 320px !important;
  }
}
</style>
